#include "Range_custom_tiling.h"
#include "kernel_operator.h"

constexpr int32_t BUFFER_NUM = 2; // tensor num for each queue

class KernelRange {
public:
    __aicore__ inline KernelRange() {}
    __aicore__ inline void Init(GM_ADDR z, float start, float step, uint32_t totalLength, uint32_t tileNum)
    {
        this->blockLength = totalLength / AscendC::GetBlockNum();
        this->tileNum = tileNum;
        this->tileLength = this->blockLength / tileNum / BUFFER_NUM;
        this->start = start;
        this->step = step;
        zGm.SetGlobalBuffer((__gm__ half *)z + this->blockLength * AscendC::GetBlockIdx(), this->blockLength);
        pipe.InitBuffer(outQueueZ, BUFFER_NUM, this->tileLength * sizeof(half));
    }
    __aicore__ inline void Process()
    {
        int32_t loopCount = this->tileNum * BUFFER_NUM;
        for (int32_t i = 0; i < loopCount; i++) {
            Compute(i);
            CopyOut(i);
        }
    }

private:
    __aicore__ inline void Compute(int32_t progress)
    {
        AscendC::LocalTensor<half> zLocal = outQueueZ.AllocTensor<half>();
        uint32_t global_offset = AscendC::GetBlockIdx() * this->blockLength + progress * this->tileLength;
        for (uint32_t i = 0; i < this->tileLength; ++i) {
            float value = this->start + (global_offset + i) * this->step;
            zLocal[i] = static_cast<half>(value);
        }
        outQueueZ.EnQue<half>(zLocal);
    }
    __aicore__ inline void CopyOut(int32_t progress)
    {
        AscendC::LocalTensor<half> zLocal = outQueueZ.DeQue<half>();
        AscendC::DataCopy(zGm[progress * this->tileLength], zLocal, this->tileLength);
        outQueueZ.FreeTensor(zLocal);
    }

private:
    AscendC::TPipe pipe;
    AscendC::TQue<AscendC::TPosition::VECOUT, BUFFER_NUM> outQueueZ;
    AscendC::GlobalTensor<half> zGm;
    uint32_t blockLength;
    uint32_t tileNum;
    uint32_t tileLength;
    float start;
    float step;
};

extern "C" __global__ __aicore__ void range_custom(GM_ADDR z, RangeCustomTilingData tiling)
{
    KernelRange op;
    op.Init(z, tiling.start, tiling.step, tiling.totalLength, tiling.tileNum);
    op.Process();
}